﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.ApplicationServices;
using System.ServiceModel.Discovery;
using System.ServiceModel;
using Devtm.ServiceModel.Configurations;

namespace Devtm.ServiceModel.Server
{

    public class HostFactory : ApplicationServicesHostFactory
    {



        protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {

            LocatorSection conf = LocatorSection.Configuration;

            Uri announcementEndpointAddress = new Uri(conf.Announcement[0].Uri);

            var r = base.CreateServiceHost(serviceType, baseAddresses);

            // Create an announcement endpoint, which points to the Announcement Endpoint hosted by the proxy service.
            AnnouncementEndpoint announcementEndpoint = new AnnouncementEndpoint(new NetTcpBinding(), new EndpointAddress(announcementEndpointAddress));

            // Create a ServiceDiscoveryBehavior and add the announcement endpoint
            ServiceDiscoveryBehavior serviceDiscoveryBehavior = new ServiceDiscoveryBehavior();
            serviceDiscoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint);

            // Add the ServiceDiscoveryBehavior to the service host to make the service discoverable
            r.Description.Behaviors.Add(serviceDiscoveryBehavior);

            /*
            System.ServiceModel.Description.ServiceMetadataBehavior smb = r.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
            {
                smb = new System.ServiceModel.Description.ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = System.ServiceModel.Description.PolicyVersion.Policy15;
                r.Description.Behaviors.Add(smb);

                // Add MEX endpoint
                r.AddServiceEndpoint(System.ServiceModel.Description.ServiceMetadataBehavior.MexContractName, System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
                // Add application endpoint
                //r.AddServiceEndpoint(typeof(MyContract), new WSHttpBinding(), "");

            }
            */

            return r;

        }


    }

}
